package com.ffggffgfv.backend.service.impl;

import com.ffggffgfv.backend.dto.ShippingAddressDTO;
import com.ffggffgfv.backend.entity.ShippingAddress;
import com.ffggffgfv.backend.mapper.ShippingAddressMapper;
import com.ffggffgfv.backend.service.ShippingAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

/**
 * 收货地址服务实现类
 */
@Service
public class ShippingAddressServiceImpl implements ShippingAddressService {

    private static final Logger logger = Logger.getLogger(ShippingAddressServiceImpl.class.getName());

    @Autowired
    private ShippingAddressMapper shippingAddressMapper;

    /**
     * 添加收货地址
     *
     * @param userId     用户ID
     * @param addressDTO 收货地址信息
     * @return 添加后的收货地址
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ShippingAddress add(Long userId, ShippingAddressDTO addressDTO) {
        // 验证参数
        if (addressDTO.getReceiverName() == null || addressDTO.getReceiverName().trim().isEmpty()) {
            throw new IllegalArgumentException("收货人姓名不能为空");
        }
        if (addressDTO.getReceiverPhone() == null || addressDTO.getReceiverPhone().trim().isEmpty()) {
            throw new IllegalArgumentException("收货人电话不能为空");
        }
        if (addressDTO.getProvince() == null || addressDTO.getProvince().trim().isEmpty() ||
                addressDTO.getCity() == null || addressDTO.getCity().trim().isEmpty() ||
                addressDTO.getDetailAddress() == null || addressDTO.getDetailAddress().trim().isEmpty()) {
            throw new IllegalArgumentException("收货地址不完整");
        }

        ShippingAddress shippingAddress = new ShippingAddress();
        shippingAddress.setUserId(userId);
        shippingAddress.setReceiverName(addressDTO.getReceiverName());
        shippingAddress.setReceiverPhone(addressDTO.getReceiverPhone());
        shippingAddress.setProvince(addressDTO.getProvince());
        shippingAddress.setCity(addressDTO.getCity());
        shippingAddress.setDistrict(addressDTO.getDistrict() != null ? addressDTO.getDistrict() : "");
        shippingAddress.setDetailAddress(addressDTO.getDetailAddress());

        // 如果是默认地址，则需要将其他地址设为非默认
        Boolean isDefault = addressDTO.getIsDefault();
        shippingAddress.setIsDefault(isDefault != null && isDefault ? 1 : 0);

        if (shippingAddress.getIsDefault() == 1) {
            shippingAddressMapper.resetDefaultAddress(userId);
        }

        // 如果是用户的第一个地址，则默认设为默认地址
        List<ShippingAddress> existingAddresses = shippingAddressMapper.selectByUserId(userId);
        if (existingAddresses.isEmpty()) {
            shippingAddress.setIsDefault(1);
        }

        shippingAddress.setCreateTime(new Date());
        shippingAddress.setUpdateTime(new Date());

        shippingAddressMapper.insert(shippingAddress);

        return shippingAddress;
    }

    /**
     * 更新收货地址
     *
     * @param userId     用户ID
     * @param id         地址ID
     * @param addressDTO 收货地址信息
     * @return 更新后的收货地址
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ShippingAddress update(Long userId, Long id, ShippingAddressDTO addressDTO) {
        // 先检查地址是否存在且属于当前用户
        ShippingAddress existingAddress = shippingAddressMapper.selectById(id);
        if (existingAddress == null || !existingAddress.getUserId().equals(userId)) {
            return null;
        }

        // 更新字段
        if (addressDTO.getReceiverName() != null) {
            existingAddress.setReceiverName(addressDTO.getReceiverName());
        }
        if (addressDTO.getReceiverPhone() != null) {
            existingAddress.setReceiverPhone(addressDTO.getReceiverPhone());
        }
        if (addressDTO.getProvince() != null) {
            existingAddress.setProvince(addressDTO.getProvince());
        }
        if (addressDTO.getCity() != null) {
            existingAddress.setCity(addressDTO.getCity());
        }
        if (addressDTO.getDistrict() != null) {
            existingAddress.setDistrict(addressDTO.getDistrict());
        }
        if (addressDTO.getDetailAddress() != null) {
            existingAddress.setDetailAddress(addressDTO.getDetailAddress());
        }

        // 处理默认地址设置
        if (addressDTO.getIsDefault() != null) {
            int newIsDefault = addressDTO.getIsDefault() ? 1 : 0;

            // 如果设为默认，则需要将其他地址设为非默认
            if (newIsDefault == 1 && existingAddress.getIsDefault() != 1) {
                shippingAddressMapper.resetDefaultAddress(userId);
            }

            existingAddress.setIsDefault(newIsDefault);
        }

        existingAddress.setUpdateTime(new Date());

        shippingAddressMapper.update(existingAddress);

        return existingAddress;
    }

    /**
     * 删除收货地址
     *
     * @param userId 用户ID
     * @param id     地址ID
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long userId, Long id) {
        // 检查是否是默认地址
        ShippingAddress address = shippingAddressMapper.selectById(id);
        if (address != null && address.getIsDefault() == 1) {
            // 如果删除的是默认地址，需要将用户的另一个地址设为默认
            List<ShippingAddress> userAddresses = shippingAddressMapper.selectByUserId(userId);
            if (userAddresses.size() > 1) {
                for (ShippingAddress a : userAddresses) {
                    if (!a.getId().equals(id)) {
                        a.setIsDefault(1);
                        shippingAddressMapper.update(a);
                        break;
                    }
                }
            }
        }

        return shippingAddressMapper.deleteById(id, userId) > 0;
    }

    /**
     * 获取用户的收货地址列表
     *
     * @param userId 用户ID
     * @return 收货地址列表
     */
    @Override
    public List<ShippingAddress> getList(Long userId) {
        return shippingAddressMapper.selectByUserId(userId);
    }

    /**
     * 根据ID获取收货地址
     *
     * @param userId 用户ID
     * @param id     地址ID
     * @return 收货地址
     */
    @Override
    public ShippingAddress getById(Long userId, Long id) {
        ShippingAddress address = shippingAddressMapper.selectById(id);
        if (address != null && address.getUserId().equals(userId)) {
            return address;
        }
        return null;
    }

    /**
     * 设置默认收货地址
     *
     * @param userId 用户ID
     * @param id     地址ID
     * @return 是否设置成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean setDefault(Long userId, Long id) {
        // 先将该用户的所有地址设为非默认
        shippingAddressMapper.resetDefaultAddress(userId);

        // 再将指定的地址设为默认
        return shippingAddressMapper.setDefaultAddress(id, userId) > 0;
    }

    /**
     * 获取用户的默认收货地址
     *
     * @param userId 用户ID
     * @return 默认收货地址
     */
    @Override
    public ShippingAddress getDefaultAddress(Long userId) {
        return shippingAddressMapper.selectDefaultAddress(userId);
    }
}
